/*-//GEN-BEGIN:copyright
 * ForBILE - Framework for Building Interactive Learning Environments
 * Computing Institute - Federal University of Alagoas - Brazil
 * Group of Otimization of the Web
 *
 * Copyright (C) 2007 Ig Bittencourt (ig.ibert@gmail.com)
 *		      Camila Nunes (camilapbnunes@hotmail.com)
 *	              Marcos Tadeu (zero.ufal@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *///GEN-END:copyright
package br.ufal.ic.forbile;

import br.ufal.ic.forbile.agents.controller.ControllerAgent;
import br.ufal.ic.forbile.exceptions.ForBILEException;
import br.ufal.ic.forbile.infra.emathema.ontology.ExternalView;
import br.ufal.ic.forbile.log.FacadeLog;
import br.ufal.ic.forbile.log.PersistenceOWLLog;
import br.ufal.ic.utils.Constants;
import br.ufal.ic.utils.RegionServer;
import br.ufal.ic.utils.SharedMem;
import edu.stanford.smi.protegex.owl.model.OWLIndividual;
import jade.Boot;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
import java.rmi.Naming;
import java.util.Map;
import java.util.logging.Logger;

/**
 * ForBILEFacade1.java
 *
 * <p>A full description of this class.
 *
 * @see SomeRelatedClass.
 *
 * @author <a href="mailto:ig.ibert@gmail.com">ig</a>.
 * @since 0.1
 * @version 0.1
 *
 */
public class ForBILEFacade {
    
    // Constants -----------------------------------------------------
    
    // Attributes ----------------------------------------------------
    
    private ControllerAgent controllerAgent;
    private ACLMessage message;
    private boolean environmentStarted = false;
    private boolean a2oCommunicationReturned = false;
    private Object objectReturned;
    // Static --------------------------------------------------------
    
    private static ForBILEFacade instance;
    private static Logger        logger;
    
    static {
        logger = Logger.getLogger(ForBILEFacade.class.getName());
    }
    
    // Constructors --------------------------------------------------
    
    /**
     * Creates a new instance of ForBILEFacade.
     */
    private ForBILEFacade() {
        Boot.main(new String[]{"-gui"});
        
        jade.core.Runtime runtime = jade.core.Runtime.instance();
        
        this.controllerAgent = new ControllerAgent("ForBILE-ManagementContainer", "ControllerAgent");
        
        Profile profile = new ProfileImpl();
        profile.setParameter(profile.CONTAINER_NAME, "ForBILE-ManagementContainer");
        
        AgentContainer controllerAgentContainer =
                runtime.createAgentContainer(profile);
        
        try {
            AgentController controller;
            controller  = controllerAgentContainer.acceptNewAgent("ControllerAgent", this.controllerAgent);
            controller.start();
        } catch (StaleProxyException ex) {
            new ForBILEException("Agent could not started", ex);
        }
        
        this.message = new ACLMessage(ACLMessage.INFORM);
        //create(new HashMap<String, Object>());
        
    }
    
    // Public --------------------------------------------------------
    
    /**
     * Gets the unique instance.
     *
     * @return The unique instance.
     */
    public static ForBILEFacade getInstance(){
        if (instance == null) {
            instance = new ForBILEFacade();
        }
        return instance;
    }
    
    /**
     * Create a cofiguration map.
     *
     * @param configuration The configuration map.
     */
    public void create(final Map configuration){
        configuration.put("Name", ExternalView.class);
        configuration.put("Individual","testequalquer");
        PersistenceOWLLog persistenceOWLLog = new PersistenceOWLLog();
        persistenceOWLLog.setConfiguration(configuration);
        persistenceOWLLog.setMethod("CREATE");
        persistenceOWLLog.setOwlFile("emathema");
        
        try {
            SharedMem mem = (SharedMem) Naming.lookup(RegionServer.HOST_URL);
            mem.getRegion(Constants.OWLPersistence).write(persistenceOWLLog);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        this.message.setContent("CREATE");
        
        requestService(this.message, "CREATE", "EMATHEMA");
    }
    
    private void requestService(ACLMessage message, String service, String ability){
        boolean flag = true;
        FacadeLog facadeLog = new FacadeLog();
        
        facadeLog.setMessage(message);
        facadeLog.setService(service);
        facadeLog.setAbility(ability);
        
        this.setA2oCommunicationReturned(false, null);
        controllerAgent.executeFacadeService(facadeLog);
    }
    
    /**
     * Retrieve the configuration map.
     *
     * @param subject The complete triple according to the semantic web
     *  structure.
     * @param predicate The complete triple according to the semantic web
     *  structure.
     * @param object The complete triple according to the semantic web
     *  structure.
     *
     * @return the configuration map.
     */
    public Map retrieve(final String subject, final String predicate,
            final String object) {
        PersistenceOWLLog persistenceOWLLog = new PersistenceOWLLog();
        persistenceOWLLog.setMethod("RETRIEVE");
        persistenceOWLLog.setOwlFile("emathema");
        persistenceOWLLog.setRetrieveKey("Map");
        persistenceOWLLog.setSubject(subject);
        persistenceOWLLog.setPredicate(predicate);
        persistenceOWLLog.setObject(object);
        
        try {
            SharedMem mem = (SharedMem) Naming.lookup(RegionServer.HOST_URL);
            mem.getRegion(Constants.OWLPersistence).write(persistenceOWLLog);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        this.message.setContent("RETRIEVE");
        
        requestService(this.message, "RETRIEVE", "EMATHEMA");
        
        
        do {
            
            if (this.getA2oCommunicationReturned()) {
                try {
                    SharedMem mem = (SharedMem) Naming.lookup(RegionServer.HOST_URL);
                    persistenceOWLLog = (PersistenceOWLLog) mem.getRegion(Constants.OWLPersistence).retrieveIfExist(persistenceOWLLog);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                
            }
        } while (!(this.getA2oCommunicationReturned()));
        
        this.objectReturned = persistenceOWLLog.getRetrieve();
        System.out.println("this.objectReturned " + this.objectReturned);
        return (Map) this.objectReturned;
    }
    
    /**
     * Retrieve the ontology individual.
     *
     * @param individual The individual name.
     * @param clazz The ontology class.
     *
     * @return The individual name.
     */
    public OWLIndividual retrieve(final String individual, final String clazz) {
        
        PersistenceOWLLog persistenceOWLLog = new PersistenceOWLLog();
        persistenceOWLLog.setMethod("RETRIEVE");
        persistenceOWLLog.setOwlFile("emathema");
        persistenceOWLLog.setRetrieveKey("Individual");
        persistenceOWLLog.setIndividual(individual);
        persistenceOWLLog.setClass_(clazz);
        
        try {
            SharedMem mem = (SharedMem) Naming.lookup(RegionServer.HOST_URL);
            mem.getRegion(Constants.OWLPersistence).write(persistenceOWLLog);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        this.message.setContent("RETRIEVE");
        
        requestService(this.message, "RETRIEVE", "EMATHEMA");
        
        do {
            
            if (this.getA2oCommunicationReturned()) {
                try {
                    SharedMem mem = (SharedMem) Naming.lookup(RegionServer.HOST_URL);
                    persistenceOWLLog = (PersistenceOWLLog) mem.getRegion(Constants.OWLPersistence).retrieveIfExist(persistenceOWLLog);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                
            }
        } while (!(this.getA2oCommunicationReturned()));
        
        this.objectReturned = persistenceOWLLog.getIndividualOWL();
        System.out.println("this.objectReturned " + this.objectReturned);
        return (OWLIndividual) this.objectReturned;
    }
    
    /**
     * Update the configuration map.
     *
     * @param configuration The configuration map.
     */
    public void update(final Map configuration){
        
    }
    
    /**
     * Delete the configuration map.
     *
     * @param configuration The configuration map.
     */
    public void delete(final Map configuration){
        
    }
    
    public void setEnvironmentStarted(boolean environmentStarted){
        this.environmentStarted = environmentStarted;
    }
    
    public void setA2oCommunicationReturned(boolean a2oCommunicationReturned, final Object object){
        this.a2oCommunicationReturned = a2oCommunicationReturned;
        this.objectReturned = object;
    }
    
    public boolean getA2oCommunicationReturned(){
        return this.a2oCommunicationReturned;
    }
    
    public Object getObjectReturned(){
        return this.objectReturned;
    }
    
// Z implementation ----------------------------------------------
    
// Y overrides ---------------------------------------------------
    
// Package protected ---------------------------------------------
    
// Protected -----------------------------------------------------
    
// Private -------------------------------------------------------
    
// Inner classes -------------------------------------------------
    
}
